package controller.product;

import com.alibaba.fastjson2.JSON;
import entity.Product;
import entity.ResultVo;
import service.ProductService;
import service.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.util.List;

@WebServlet("/pro/test")
public class ProductController extends HttpServlet {
    private ProductService proservice =new ProductServiceImpl();
    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        //一、模拟数据
        //1.查询所有的产品信息
        List<Product> productList1= proservice.findAll();
        //2. 根据产品名称进行模糊查询
        List<Product> productList2 = proservice.findByLikeUsername("M");
        //3. 根据产品的类型的id进行精确查询
        Product pro =proservice.getById(1);

        //二、定义一个result对象
        ResultVo resultVo1 = new ResultVo("001","查询所有的产品信息",productList1);
        ResultVo resultVo2 = new ResultVo("001","根据产品名称进行模糊查询",productList2);
        ResultVo resultVo3 = new ResultVo("003","根据产品的类型的id进行精确查询",pro);
        //目的-> resultVo(java对象)=> json字符串 => 返回到页面中去.

        //三、设置文档的输出类型
        resp.setContentType("text/json;charset=utf-8");

        //四、获取文档的输出流
        PrintWriter out = resp.getWriter();

        //五、java对象转成json字符串
        String resultVoStr1 = JSON.toJSONString(resultVo1);
        String resultVoStr2 = JSON.toJSONString(resultVo2);
        String resultVoStr3 = JSON.toJSONString(resultVo3);
        //六、返回出去
        out.println(resultVoStr1);
        out.println(resultVoStr2);
        out.println(resultVoStr3);
    }
}
